# encoding: utf-8
"""
为了让系统更加容易更新，特意提供了这个更新工具，在不想将整个系统删除的情况下进行对固定格式的更新进行解析，从而更新自身
注意：本工具对python脚本及exe文件皆有效果,前提是更新包与之相对应
"""
import sys
import os
import shelve
import shutil
from Error.Error import send_error
from share import ver


def backup(path):
    """更新之前先备份系统
    path：备份的文件路径
    """
    try:
        b_path = os.path.join(
            os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "backup"
        )
        os.mkdir(b_path)
    except FileExistsError:
        pass
    shutil.copytree(path, f"{b_path}\\Tree")


def update(path: str):
    path = os.path.abspath(path)
    # 验证真假：文件和文件中的键
    try:
        yn = shelve.open(os.path.join(path, "update"))
        if yn.get("update") is None:
            send_error(
                "RunError",
                f"tool 'update' couldn't use the {os.path.join(path, 'update.dat')} because it is false.",
            )
    except FileNotFoundError:
        send_error(
            "RunError", f"tool 'update' couldn't the {os.path.join(path, 'update.dat')}"
        )
    else:
        # 检测版本条件
        biggest_ver = float(yn["biggest_ver"])
        smallest_ver = float(yn["smallest_ver"])
        if not (smallest_ver <= ver < biggest_ver):
            # 不满足条件
            send_error("RunError", f"update's ver is {smallest_ver}")
        elif ver == biggest_ver:
            print("Tree updated.")
            sys.exit()

        update_file_list: dict = yn["files"]
        main_path = os.path.dirname(os.path.dirname(__file__))
        # 备份系统
        backup(main_path)
        # 更新
        for newfile in update_file_list:
            new = os.path.join(path, newfile)
            old = os.path.join(main_path, newfile)
            if os.path.isfile(new):
                os.remove(old)
                shutil.copyfile(new, old)
            elif os.path.isdir(new):
                shutil.rmtree(old)
                shutil.copytree(new, old)
            else:
                print(f"Error:could'n find {new}")
            print(f"updating {new}, {old}")
        print(f"updated all!")

        # 删除更新包
        shutil.rmtree(path)


if __name__ == "__main__":
    file_list = sys.argv[1:]
    for i in file_list:
        update(i)
